<?php

/**
 * @author: caipeichao
 */
require_once(APP_PATH . 'Home/Common/function.php');


/**帖子内容图片分离
 * @param $aContent
 * @return mixed
 */
function text_part($aContent)
{

    $arr=array();
    preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/", $aContent, $arr); //匹配所有的图片

    $data ['image'] = $arr[1];
    $data['content'] = op_t($aContent);

    return $data;
}
///**
// * 登录指定用户
// * @param  integer $uid 用户ID
// * @param bool $remember
// * @param int $role_id 有值代表强制登录这个角色
// * @return boolean      ture-登录成功，false-登录失败
// */
// function mobileLogin($uid, $remember = false, $role_id = 0){
//    /* 检测是否在当前应用注册 */
//    $user =D('Member')->field(true)->find($uid);
//    if ($role_id != 0) {
//        $user['last_login_role'] = $role_id;
//    } else {
//        if (!intval($user['last_login_role'])) {
//            $user['last_login_role'] = $user['show_role'];
//        }
//    }
//    session('temp_login_uid', $uid);
//    session('temp_login_role_id', $user['last_login_role']);
//
//    if ($user['status'] == 3 /*判断是否激活*/) {
//        header('Content-Type:application/json; charset=utf-8');
//        $data['status'] = 1;
//        $data['url'] = U('Ucenter/Member/activate');
//        exit(json_encode($data));
//    }
//
//    if (1 != $user['status']) {
//        $this->error = '用户未激活或已禁用！'; //应用级别禁用
//        return false;
//    }
//    autoLogin($user, $remember);
//
//    session('temp_login_uid', null);
//    session('temp_login_role_id', null);
//    //记录行为
//    action_log('user_login', 'member', $uid, $uid);
//    return true;
//
//}
 function autoLogin($user, $remember = false, $role_id = 0)
{

    /* 更新登录信息 */
    $data = array(
        'uid' => $user['uid'],
        'login' => array('exp', '`login`+1'),
        'last_login_time' => NOW_TIME,
        'last_login_ip' => get_client_ip(1),
        'last_login_role' => $user['last_login_role'],
    );
    D('Member')->save($data);
    //判断角色用户是否审核
    $map['uid'] = $user['uid'];
    $map['role_id'] = $user['last_login_role'];
    $audit = D('UserRole')->where($map)->getField('status');
    //判断角色用户是否审核 end

    /* 记录登录SESSION和COOKIES */
    $auth = array(
        'uid' => $user['uid'],
        'username' => get_username($user['uid']),
        'last_login_time' => $user['last_login_time'],
        'role_id' => $user['last_login_role'],
        'audit' => $audit,
    );
    session('user_auth', $auth);
    session('user_auth_sign', data_auth_sign($auth));
    if ($remember) {
        $user1 = D('user_token')->where('uid=' . $user['uid'])->find();
        $token = $user1['token'];
        if ($user1 == null) {
            $token = build_auth_key();
            $data['token'] = $token;
            $data['time'] = time();
            $data['uid'] = $user['uid'];
            D('user_token')->add($data);
        }
    }

    if (!getCookieUid() && $remember) {
        $expire = 3600 * 24 * 7;
        cookie('OX_LOGGED_USER', $this->jiami($this->change() . ".{$user['uid']}.{$token}"), $expire);
    }
}


function need_login()
{
    if (!is_login()) {
        if ($uid =D('user_token')->getCookieUid()) {
            $this->login($uid);
            return true;
        }
    }

}

function getCookieUid()
{

    static $cookie_uid = null;
    if (isset($cookie_uid) && $cookie_uid !== null) {
        return $cookie_uid;
    }
    $cookie = cookie('OX_LOGGED_USER');
    $cookie = explode(".", jiemi($cookie));
    $map['uid'] = $cookie[1];
    $user = D('user_token')->where($map)->find();
    $cookie_uid = ($cookie[0] != change()) || ($cookie[2] != $user['token']) ? false : $cookie[1];
    $cookie_uid = $user['time'] - time() >= 3600 * 24 * 7 ? false : $cookie_uid;
    return $cookie_uid;
}


/**
 * 加密函数
 * @param string $txt 需加密的字符串
 * @param string $key 加密密钥，默认读取SECURE_CODE配置
 * @return string 加密后的字符串
 */
function jiami($txt, $key = null)
{
    empty($key) && $key =change();

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_";
    $nh = rand(0, 64);
    $ch = $chars[$nh];
    $mdKey = md5($key . $ch);
    $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
    $txt = base64_encode($txt);
    $tmp = '';
    $i = 0;
    $j = 0;
    $k = 0;
    for ($i = 0; $i < strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = ($nh + strpos($chars, $txt [$i]) + ord($mdKey[$k++])) % 64;
        $tmp .= $chars[$j];
    }
    return $ch . $tmp;
}

/**
 * 解密函数
 * @param string $txt 待解密的字符串
 * @param string $key 解密密钥，默认读取SECURE_CODE配置
 * @return string 解密后的字符串
 */
function jiemi($txt, $key = null)
{
    empty($key) && $key = change();

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_";
    $ch = $txt[0];
    $nh = strpos($chars, $ch);
    $mdKey = md5($key . $ch);
    $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
    $txt = substr($txt, 1);
    $tmp = '';
    $i = 0;
    $j = 0;
    $k = 0;
    for ($i = 0; $i < strlen($txt); $i++) {
        $k = $k == strlen($mdKey) ? 0 : $k;
        $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
        while ($j < 0) {
            $j += 64;
        }
        $tmp .= $chars[$j];
    }

    return base64_decode($tmp);
}

function change()
{
    preg_match_all('/\w/', C('DATA_AUTH_KEY'), $sss);
    $str1 = '';
    foreach ($sss[0] as $v) {
        $str1 .= $v;
    }
    return $str1;
}
function getCheck($uid){
    $time = get_some_day(0);
    $res = S('check_in_'.$uid.'_'.$time);
    if(empty($res)){
        $res = $this->where(array('uid'=>$uid,'create_time'=>array('egt',$time)))->find();
        $check = query_user(array('con_check','total_check'),$uid);
        $res = array_merge($res,$check);
        S('check_in_'.$uid.'_'.$time,$res,60*60*24);
    }
    return $res;
}

function addCheck($uid){
    $data['uid'] = $uid;
    $data['create_time'] = time();
    return $this->add($data);
}


function checkYesterday($uid)
{
    $memberModel = D('Member');
    $time = get_some_day(0);
    $time_yesterday = get_some_day(1);
    $check = $this->where(array('uid' => $uid, 'create_time' => array('between', array($time_yesterday, $time))))->find();
    if ($check) {
        $memberModel->where(array('uid' => $uid))->setInc('con_check');
    } else {
        $memberModel->where(array('uid' => $uid))->setField('con_check', 1);
    }
}

function getRank($type){
    $time = get_some_day(0);
    $time_yesterday = get_some_day(1);
    $memberModel = D('Member');
    switch($type){
        case 'today' :
            $list = $this->where(array('create_time'=>array('egt',$time)))->order('create_time asc')->limit(5)->select();
            break;
        case 'con' :
            $uids = $this->where(array('create_time'=>array('egt',$time_yesterday)))->field('uid')->select();
            $uids = getSubByKey($uids,'uid');
            $list = $memberModel ->where(array('uid'=>array('in',$uids)))->field('uid,con_check')->order('con_check desc,uid asc')->limit(5)->select();
            break;
        case 'total' :
            $list = $memberModel ->field('uid,total_check')->order('total_check desc,uid asc')->limit(5)->select();
            break;
    }

    foreach($list as &$v){
        $v['user'] = query_user(array('avatar32','avatar64','space_url', 'nickname', 'uid',), $v['uid']);
    }
    unset($v);
    return $list;
}